package com.dd.keel.core.common.utils;

import java.io.ByteArrayOutputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ArrayUtil {
		
	final static private Logger LOGGER = LoggerFactory.getLogger(ArrayUtil.class);
	
	public static String[] addParamToArray(String[] paramArray,String paramName,String paramValue)
	{
		String[] tempArray = null;
		if(paramArray==null)
		{
			tempArray = new String[]{paramName,paramValue};
		}else{
			int length = paramArray.length;
			tempArray = new String[length+2];
			for(int i=0; i<length; i++)
			{
				tempArray[i] = paramArray[i];
			}
			tempArray[length] = paramName;
			tempArray[length+1] = paramValue;
		}
		return tempArray;
	}
	
	public static String getParamFromPairArray(String[] paramArray,String paramName)
	{
		if(paramName==null || paramArray==null || paramArray.length %2 !=0) return null;
		String temp = null;
		for(int i=0; i<paramArray.length; i=i+2)
		{
			if(paramName.equalsIgnoreCase(paramArray[i]))
			{
				temp = paramArray[i+1];
				break;
			}
		}
		return temp;
	}
	
	public static byte[] getValidDatagramBytes(byte[] datagram)
	{
		if(datagram==null) return null;
		byte[] temp = null;
		ByteArrayOutputStream baos= null;
		try{
			baos = new ByteArrayOutputStream();
			for(int i=0; i<datagram.length; ++i){
				if( datagram[i] != 0x00 ){
					baos.write(datagram[i]);
				}else{
					break;
				}
			}
			temp = baos.toByteArray();
		}catch(Exception ex){
			LOGGER.error( ex.getMessage(), ex );
		}finally{
			try{
				baos.close();
			}catch(Exception e){
				LOGGER.error( e.getMessage(), e );
			}
		}
		return temp;
	}
	
}
